import React, {Component} from 'react';
import {
  Table,
  Badge,
  Card,
  Input,
  Select,
  message,
  Modal,
} from 'antd';

import {connect} from "dva";
import SearchForm from '../../components/AutoForm/SearchForm';
import EditForm from '../../components/AutoForm/EditForm';

const {Option} = Select;
const {TextArea} = Input;
const confirm = Modal.confirm;


const statusMap = ['processing', 'warning'];
const status = ['使用中', '锁定'];

const searchFields = [
  {
    cols: [
      {
        md: 6,
        label: '名称',
        name: 'name',
        component: <Input placeholder="请输入"/>
      },
      {
        md: 6,
        label: '编码',
        name: 'code',
        component: <Input placeholder="请输入"/>
      },
      {
        md: 6,
        label: '使用状态',
        name: 'isLock',
        component: <Select placeholder="请选择" style={{width: '100%'}}>
          <Option value="0">使用中</Option>
          <Option value="1">锁定</Option>
        </Select>
      }
    ]
  }
];



@connect(({resourceType, loading}) => ({
  tableLoading: loading.effects['resourceType/page'],
  tableData: resourceType.list,
  modalUpdateLoading: loading.effects['resourceType/update'],
  modalInsertLoading: loading.effects['resourceType/insert'],
  searchForm: resourceType.searchForm,
  modalForm: resourceType.modalForm,
  addForm: resourceType.addForm,
  modalVisible: resourceType.modalVisible,
  selection: resourceType.selection,
  optFlag: resourceType.optFlag
}))
export default class Type extends Component {
  columns = [
    {
      key: 1,
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '编码',
      dataIndex: 'code',
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '描述',
      dataIndex: 'descr',
    },
    {
      title: '锁定/使用',
      dataIndex: 'isLock',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]}/>;
      },
    }
  ];

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'resourceType/page',
    })
  }

  handleSearch = () => {
    const {dispatch, searchForm} = this.props;
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const param = {
      ...searchValue,
    };
    dispatch({
      type: 'resourceType/page',
      payload: param
    })
  }

  handleSearchChange = (fields) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'resourceType/handleSearchChange',
      payload: fields
    })
  }

  handleModalVisible = (opt) => {
    const {dispatch, modalVisible, selection, addForm} = this.props;
    let payload = {modalVisible: !modalVisible};
    let modalForm = {};
    if ('edit' === opt) {
      if (JSON.stringify(selection) === '{}') {
        message.error('请选择一条记录');
        return;
      } else {
        Object.keys(selection).map((key) => {
          modalForm[key] = {value: selection[key]}
        })
      }
    } else if ("add" === opt) {
      Object.keys(addForm).map((key) => {
        modalForm[key] = {value: addForm[key]}
      })
    }

    if (!modalVisible) {
      payload.optFlag = opt;
      payload.modalForm = modalForm;
    }
    dispatch({
      type: 'resourceType/handleModalVisible',
      payload: payload
    })
  }

  handleOk = (fields) => {
    const {dispatch, optFlag, searchForm} = this.props;
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const payload = {
      fields: fields,
      searchForm: searchValue
    }
    if (optFlag === 'add') {
      dispatch({
        type: 'resourceType/insert',
        payload: payload
      })
    } else if (optFlag === 'edit') {
      dispatch({
        type: 'resourceType/update',
        payload: payload
      })
    }
  }

  handleDel = () => {
    const {dispatch, selection, searchForm} = this.props;
    if (JSON.stringify(selection) === '{}') {
      message.error('请选择一条记录');
      return;
    }
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const payload = {
      fields: selection,
      searchForm: searchValue
    }
    confirm({
      title: '是否确认删除此公司类型?',
      content: `编码：${selection.code}; 名称：${selection.name}`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'resourceType/del',
          payload: payload,
        });
      },
    });
  }

  handleModalChange = (fields) => {
    const {dispatch, optFlag, addForm} = this.props;
    const payload = {fields: fields, optFlag: optFlag, addForm: addForm};
    dispatch({
      type: 'resourceType/handleModalChange',
      payload: payload
    })
  }

  onSelect = (record) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'resourceType/handleTableSelection',
      payload: record
    })
  };

  render() {
    const {tableLoading, tableData, searchForm, modalForm, modalVisible, optFlag, modalUpdateLoading, modalInsertLoading} = this.props;
    const rowSelection = {
      type: "radio",
      onSelect: this.onSelect
    }
    const EditRows = [
      {
        cols: [
          {
            label: '名称',
            name: 'name',
            md: 18,
            rules: [{required: true, message: '请输入至少四个字符！', min: 4}],
            component: <Input placeholder="请输入名称"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '编码',
            name: 'code',
            md: 18,
            rules: [{required: true, message: '请输入至少四个字符！', min: 4}],
            component: <Input disabled={optFlag === 'add' ? false : true} placeholder="请输入编码"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '描述',
            name: 'descr',
            md: 18,
            component: <TextArea placeholder="请输入描述"/>
          },
          {
            name: 'id',
            md: 0,
            component: <Input type={'hidden'}/>
          },
        ]
      },
    ]
    return (
      <Card bodyStyle={{padding: 0}}>
        <SearchForm
          header="资源类型->操作"
          layout="inline"
          fields={searchFields}
          fieldValue={searchForm}
          onSubmit={this.handleSearch}
          onModal={this.handleModalVisible}
          onFieldsChange={this.handleSearchChange}
          onDel={this.handleDel}
        />
        <Table
          columns={this.columns}
          loading={tableLoading}
          dataSource={tableData}
          rowSelection={rowSelection}
          rowKey={record => record.id}
          scroll={{x: 'max-content'}}
          size="small"
          bordered/>
        <EditForm
          rows={EditRows}
          fieldValue={modalForm}
          optFlag={optFlag}
          visible={modalVisible}
          confirmLoading={modalUpdateLoading || modalInsertLoading}
          onFieldsChange={this.handleModalChange}
          onOk={this.handleOk}
          onCancel={this.handleModalVisible}
        />
      </Card>
    );
  }
}
